<?php
/**
 * 公告信息
 * User: Tommy
 * Date: 2018/11/13
 * Time: 14:46
 */

namespace App\Services;


use App\Models\Hall;
use App\Models\HallMessage;
use App\Models\HallMessageRecord;
use App\Models\MasterUser;
use common\enum\CommonEnum;
use common\enum\MasterLogEnum;
use common\utils\SysCode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class NoticeService
{
    const SHOW_DISABLE = 0;
    const SHOW_ENABLED = 1;

    const type = [
        1 => '第三方游戏消息',
        2 => '财务消息',
        3 => '平台维护消息'
    ];

    /**
     * 获取厅主名称
     * @return array|bool
     */
    public static function getHallName()
    {
        $select = ['company_name as name', 'id'];
        $data   = Hall::select($select)
            ->get()
            ->toArray();
        return $data;
    }

    /**
     * 添加公告信息
     * @param array $values
     * @return mixed
     * @throws \App\Exceptions\CustomException
     */
    public static function addinfo(array $values)
    {
        $user = Auth::user();
        foreach ($values['hall_id'] as $key => $val) {
            $userId[] = $val['id'];
        }
        $update['master_user_id']  = $user['id'];
        $update['master_username'] = $user['username'];
        $update['hall_ids']        = implode(',', $userId);
        $update['title']           = $values['title'];
        $update['content']         = $values['content'];
        $update['type']            = $values['type'];
        $update['show_type']       = self::SHOW_ENABLED;
        $update['status']          = CommonEnum::ENABLED;
        $messageId = '';
        try {
            DB::beginTransaction();//开启事物
            $messageId = HallMessage::insertGetId($update);
            if (!$messageId) {
                error_exit(SysCode::BULLETIN_ADD_ERROR);
            } else {
                self::addMessageRecord($messageId, $values['hall_id']);
            }
        } catch (\Exception $e) {
            Db::rollback(); //事物回滚
            error_exit(SysCode::BULLETIN_ADD_ERROR);
        }
        DB::commit();//事物提交
        /********日志写入********/
        $hallName = [];
        foreach ($values['hall_id'] as $value) {
            $hallName[] = $value['name'];
        }
        $remark = str_replace(['{:title}'],[$update['title']],MasterLogEnum::REMARK['notice_send']);
        MasterLogService::writeMasterLog(MasterLogEnum::NOTICE_SEND, MasterLogEnum::SUCCESS, $remark);
        return $messageId;
    }

    /**
     * 添加厅主记录
     * @param $messageId
     * @param $hallData
     * @return bool
     * @throws \App\Exceptions\CustomException
     */
    public static function addMessageRecord($messageId, $hallData)
    {
        foreach ($hallData as $value) {
            $update['message_id'] = $messageId;
            $update['hall_id']    = $value['id'];
            $update['hall_name']  = $value['name'];
            $update['status']     = CommonEnum::DISABLE;
            $result               = HallMessageRecord::insert($update);
            if (!$result) {
                error_exit(SysCode::BULLETIN_ADD_RECORD_ERROR);
            }
        }
        return true;
    }

    /**
     * 公告列表入口
     * @param array $values
     * @return array|mixed
     */
    public static function noticeInfo(array $values)
    {
        return !empty($values['id']) ? self::infoDetails($values['id']) : self::noticeList($values);
    }

    /**
     * 查询SQL
     * @return \Illuminate\Database\Query\Builder
     */
    public static function selectSql()
    {
        $select = ['a.id', 'a.title', 'a.hall_ids', 'a.type', 'a.created_at', 'a.master_username', 'a.status', 'a.content'];
        $query  = DB::table('hall_message as a')
            ->leftJoin('hall_message_record as b', 'a.id', '=', 'b.message_id')
            ->select($select)
            ->selectRaw("GROUP_CONCAT(b.hall_name) as hall_name")
            ->selectRaw("SUM(IF(b.status>0,1,0)) as see")
            ->selectRaw("COUNT(b.id) as sum")
            ->groupBy('a.id')
            ->orderBy('a.created_at','DESC');
        return $query;
    }

    /**
     * 公告查询
     * @param $values
     * @return array
     */
    public static function query($values)
    {
        $query = self::selectSql();
        if (!empty($values['user_id']) || isset($values['user_id'])) {
            $query->where(['master_user_id' => $values['user_id']]);
        }
        if (!empty($values['hall_id'])) {
            $query->whereRaw("LOCATE('" . trim($values['hall_id']) . "', hall_ids)");
        }
        if (!empty($values['type'])) {
            $query->where(['type' => $values['type']]);
        }
        if (!empty($values['start_time']) && !empty($values['end_time'])) {
            $query->whereBetween('a.created_at', [$values['start_time'], $values['end_time']]);
        }
        $data = self::noticeList($values, true, $query);
        return $data;
    }

    /**
     * 搜索公告列表
     * @param $values
     * @param bool $where
     * @param string $query
     * @return array
     */
    public static function noticeList($values, $where = false, $query = '')
    {
        unset($values['id']);
        if (!$where) {
            $query = self::selectSql();
        }
        $page = $values['page'] ?? CommonEnum::PAGE_DEFAULT;
        $size = $values['page_size'] ?? CommonEnum::PAGE_SIZE_TWENTY;
        $data = get_page_data($query, $page, $size);
        return $data;
    }

    /**
     * 查询单条公告详情
     * @param int $id
     * @return mixed
     */
    public static function infoDetails(int $id)
    {
        $select = ['type', 'created_at', 'title', 'content'];
        return HallMessage::select($select)->where(['id' => $id])->first();
    }

    /**
     *  撤回
     */
    public static function revert(int $id, int $status)
    {
        $result = HallMessage::where(['id' => $id])->update(['status' => $status]);
        if ($result) {
            $hallMessage = HallMessage::where(['id' => $id])->first();
            $remark = str_replace(['{:title}'],[$hallMessage['title']],MasterLogEnum::REMARK['notice_withdraw']);
            MasterLogService::writeMasterLog(MasterLogEnum::NOTICE_WITHDRAW, MasterLogEnum::SUCCESS, $remark);
        }
        return $result;
    }

    /**
     * 获取管理员名字和ID
     * @return mixed
     */
    public static function likeQuery()
    {
        $data = MasterUser::select('id', 'username')->get()->toArray();
        $data = array_merge($data, [['id' => 0, 'username' => '系统']]);//['id' => 0, 'username' => '系统']是跟系统下发预警公告功能约定好的，方便公告搜索
        return $data;
    }

    /**
     * 二維數組根據value去重
     * @param $arr
     * @param $key
     * @return array
     */
    public static function array_unset_tt($arr, $key)
    {
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if (isset($res[$value[$key]])) {
                //有：销毁
                unset($value[$key]);
            } else {
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }


    /**
     * 数组降维
     * @param $arr
     * @return array|bool
     */
    public static function multiToSingle($arr)
    {
        $resultAry = array();
        if (!(is_array($arr) && count($arr) > 0)) {
            return false;
        }
        foreach ($arr AS $k => $val) {
            if (is_array($val) && count($val) > 0) {
                $resultAry = array_merge($resultAry, self::multiToSingle($val));
            } else {
                $resultAry[] = $val;
            }
        }
        return $resultAry;
    }

    /**
     * 统计公告查看状态
     * @param $noticeId
     * @return mixed
     */
    public static function sumStatus($noticeId)
    {
        return HallMessageRecord::select('hall_name', 'status')->where(['message_id' => $noticeId])->get();
    }
}